﻿package demo.app.view
{
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.*;
	
	import demo.app.Constants;
	import demo.app.factory.ShapeFactory;
	import demo.app.model.vo.PolyShapeVO;
	
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class ShapeEnvironment extends Base2dEnvironment
	{    
		public var gravityX:Number = 0;
		public var gravityY:Number = 0;
		
		public function ShapeEnvironment(boxWidth:int = 800, boxHeight:int = 500, debugMode:Boolean = false)
		{
			super(boxWidth, boxHeight, debugMode);
		}
		
		/*
		* PUBLIC FUNCTIONS
		*/                
		public function addPoly(shapeVO:PolyShapeVO):void
		{
			var squareClip:Sprite = ShapeFactory.generateSquareSprite(shapeVO);
			
			if(debug_mode)
			{squareClip.alpha = 0.5;}
			
			addChild(squareClip);
			
			var bd:b2BodyDef = ShapeFactory.generateBodyDef(squareClip, shapeVO.xPos, shapeVO.yPos);
			var cd:b2FixtureDef = ShapeFactory.generateSquareDef(shapeVO);
			
			addShape(bd, cd);            
		}
		
		override protected function update(e:Event):void
		{
			super.update(e);
			
			for (var bb:b2Body = world.GetBodyList(); bb; bb=bb.GetNext()) {
				if (bb.GetUserData() is Sprite) {
					world.SetGravity(new b2Vec2(gravityX, gravityY));
					
					var sprite:Sprite = bb.GetUserData() as Sprite;
					sprite.x = bb.GetPosition().x * Constants.PHYS_SCALE;
					sprite.y = bb.GetPosition().y * Constants.PHYS_SCALE;
					sprite.rotation = bb.GetAngle() * 180 / Math.PI;
				}
			}  
		}
		
		private function addShape(bd:b2BodyDef, cd:b2FixtureDef):void
		{
			var x_speed:Number = Math.random() * 10;
			
			body = world.CreateBody(bd);
			body.CreateFixture(cd);

			// Assign a random speed to the shape
			//body.m_linearVelocity.x = x_speed;
			//body.m_linearVelocity.y = 10 - x_speed;                        
		}
	}
}